package com.tql.test_15;

import java.util.concurrent.TimeUnit;
/*  （互相抱有对方的资源不释放）
* 1.互斥条件:一个资源每次只能被一个进程使用;
2.请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放;
3.不剥夺条件:进程已获得的资源,在末使用完之前,不能强行剥夺;
4.循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系;
* */
public class DeadLock {
    public static void main(String[] args) {
        DeadLockTest deadLockTest = new DeadLockTest("lockA", "lockB");
        DeadLockTest deadLockTest1 = new DeadLockTest("lockB", "lockA");
        new Thread(deadLockTest,"线程A").start();
        new Thread(deadLockTest1,"线程B").start();

    }
}
class DeadLockTest implements Runnable{
    private String locka;
    private String lockb;

    public DeadLockTest(String locka, String lockb) {
        this.locka = locka;
        this.lockb = lockb;
    }

    @Override
    public void run() {
        synchronized (locka){
            System.out.println(Thread.currentThread().getName()+"获得资源"+lockb);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lockb){
                System.out.println(Thread.currentThread().getName()+"获得资源"+locka);
            }
        }
    }
}